package com.example.tanloadpic;

import android.graphics.Bitmap;
import android.os.Handler;

import com.example.tanloadpic.handle.RequestHandler;

import java.io.IOException;

import java.util.List;


public class BitmapHunter implements Runnable {
    private final List<RequestHandler> mRequestHandlerList;

    public RequestData mData;
    private TanLoadPic tanLoadPic;
    private final Handler mDispatcherHandler;
    private Bitmap mResult;
    public TanLoadPic mTanLoadPic;

    public BitmapHunter(RequestData data, TanLoadPic tanLoadPic, Dispatcher dispatcher) {
        this.mData = data;
        this.tanLoadPic = tanLoadPic;
        this.mTanLoadPic = TanLoadPic.instance;
        this.mDispatcherHandler = dispatcher.mHandler;
        this.mRequestHandlerList = TanLoadPic.instance.mRequestHandlerList;


    }

    @Override
    public void run() {
        try {

            mResult = hunt();

        } catch (IOException e) {
            e.printStackTrace();
        }
        mDispatcherHandler.sendMessage(mDispatcherHandler.obtainMessage(Dispatcher.TASK_COMPLETE,this ));
    }

    private Bitmap hunt() throws IOException {
        Bitmap bitmap = null;

        for (int i = 0; i < mRequestHandlerList.size(); i++) {

            bitmap = hunt(mRequestHandlerList.get(i));
            if (bitmap!=null) {
                return bitmap;
            }


        }
        return null;


    }


    private Bitmap hunt(RequestHandler requestHandler) throws IOException {
        Bitmap bitmap = requestHandler.load(mTanLoadPic, mData);

        String mLoadHandlerFrom = requestHandler.loadSource();


        if (bitmap != null) {
            System.out.println("奇怪哦");
            RequestCreator.CompressConfig compressConfig = mData.mCompressConfig;
            if (compressConfig != null){

                bitmap = compressConfig.Compress(bitmap);
            }

            mTanLoadPic.mMemoryCache.put(mData.key, bitmap);

        }
        return bitmap;
    }


    public Bitmap getBitmapResult() {
        return mResult;
    }
}
